package com.common.server.common.config;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 描述：Nacos 配置类
 * <p>
 * 作者：HuTongFu
 * 时间：2019/6/28 16:37
 */
@Slf4j
//@Configuration
public class NacosConfig {

    @Resource
    private SysCommonConfig sysCommonConfig;

    // 注入 Nacos 的 NamingService 实例
    @NacosInjected
    private NamingService namingService;

    @Value("${server.port}")
    private int serverPort;

    @Value("${spring.application.name}")
    private String applicationName;

    @PostConstruct
    public void registerInstance() throws NacosException {
        namingService.registerInstance(applicationName, sysCommonConfig.getNacosServerAddress(), serverPort);
        String server = sysCommonConfig.getNacosServerAddress() + ":" + serverPort;
        namingService.subscribe(applicationName, event -> {
            log.debug("服务[{}]注册到[{}]成功", ((NamingEvent) event).getServiceName(), server);
        });
    }


}
